import axios, { type AxiosResponse } from 'axios'

interface DownloadOptions {
  url: string
  method?: 'get' | 'post'
  params?: Record<string, any>
  fileName?: string
}

/**
 * 通用文件下载函数
 * @param options 下载配置项
 * @returns Promise<void>
 */
export const downloadFile = async (options: DownloadOptions): Promise<void> => {
  try {
    const response: AxiosResponse<Blob> = await axios({
      url: options.url,
      method: options.method || 'get',
      params: options.params,
      responseType: 'blob' // 强制声明二进制响应类型‌:ml-citation{ref="4,5" data="citationList"}
    })

    // 验证是否为有效文件流‌:ml-citation{ref="3" data="citationList"}
    if (!(response.data instanceof Blob)) {
      throw new Error('无效的文件流响应')
    }

    // 解析文件名‌:ml-citation{ref="3,4" data="citationList"}
    // const filename = options.fileName || parseFilename(response.headers)
    const filename = options.fileName || `download_${Date.now()}`

    // 创建下载链接‌:ml-citation{ref="4,5" data="citationList"}
    const blob = new Blob([response.data], { type: response.headers['content-type'] })
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = filename
    document.body.appendChild(link)
    link.click()
    
    // 清理资源‌:ml-citation{ref="5,6" data="citationList"}
    window.URL.revokeObjectURL(downloadUrl)
    document.body.removeChild(link)
  } catch (error) {
    console.error('文件下载失败:', error)
    throw error
  }
}

// 响应头文件名解析‌:ml-citation{ref="3,4" data="citationList"}
// const parseFilename = (headers: Record<string, string>): string => {
//   const disposition = headers['content-disposition'] || ''
//   const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
//   const matches = filenameRegex.exec(disposition)
  
//   return matches 
//     ? decodeURIComponent(matches‌:ml-citation{ref="1" data="citationList"}.replace(/['"]/g, '')) 
//     : `download_${Date.now()}`
// }
